package com.jtech.together.receive;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import com.jtech.together.R;
import com.jtech.together.manager.UserManager;
import com.jtech.together.model.AddFriendMessage;
import com.jtech.together.model.AgreeAddFriendMessage;
import com.jtech.together.model.event.AcceptEvent;
import com.jtech.together.model.event.InChatEvent;
import com.jtech.together.model.event.ReceiveMessageEvent;
import com.jtech.together.util.Bus;
import com.jtech.together.util.IM;
import com.jtech.together.util.ImageUtils;
import com.jtech.together.util.JNotify;
import com.jtech.together.view.activity.ChatActivity;
import com.jtech.together.view.activity.MainActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
import cn.bmob.newim.listener.BmobIMMessageHandler;
import io.reactivex.functions.Consumer;

/**
 * 即时通讯消息处理
 * Created by wuxubaiyang on 2017/5/10.
 */

public class IMMessageHandler extends BmobIMMessageHandler {
    private Context context;
    private String conversationId;

    public IMMessageHandler(Context context) {
        this.context = context;
        //上车
        Bus.getOn(this);
    }

    @Override
    public void onMessageReceive(MessageEvent messageEvent) {
        //更新用户信息
        updateIMUserInfo(messageEvent.getFromUserInfo());
        //更新未读消息
        updateUnReadCount(messageEvent.getConversation());
        //消息接收
        Bus.get().post(new ReceiveMessageEvent(messageEvent.getMessage()));
        //显示通知栏消息
        showNotifyMessage(messageEvent);
        //如果是接受邀请消息则发送对应消息
        if (AgreeAddFriendMessage.isAgreeAddFriend(messageEvent.getMessage())) {
            Bus.get().post(new AcceptEvent(messageEvent.getFromUserInfo().getUserId()));
        }
    }

    @Override
    public void onOfflineReceive(OfflineMessageEvent offlineMessageEvent) {
        //更新离线消息的用户信息
        updateOfflineMessageUserInfo(offlineMessageEvent.getEventMap());
    }

    /**
     * 更新离线消息的用户信息
     *
     * @param map
     */
    private void updateOfflineMessageUserInfo(Map<String, List<MessageEvent>> map) {
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            List<MessageEvent> messageEvents = map.get(key);
            MessageEvent messageEvent = messageEvents.get(0);
            //更新最新一条消息的用户信息
            updateIMUserInfo(messageEvent.getFromUserInfo());
            //遍历更新离线消息的未读数
            BmobIMConversation conversation = messageEvent.getConversation();
            updateUnReadCount(conversation,
                    conversation.getUnreadCount() + messageEvents.size());
        }
    }

    /**
     * 进入或退出聊天室的事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void InChatEvent(InChatEvent event) {
        this.conversationId = event.getConversationId();
    }

    /**
     * 更新用户信息
     *
     * @param userInfo
     */
    private void updateIMUserInfo(BmobIMUserInfo userInfo) {
        UserManager.updateIMUserInfo(userInfo);
    }

    /**
     * 更新未读消息数
     *
     * @param conversation
     */
    private void updateUnReadCount(BmobIMConversation conversation) {
        updateUnReadCount(conversation, conversation.getUnreadCount() + 1);
    }

    /**
     * 更新未读消息数
     *
     * @param conversation
     * @param count
     */
    private void updateUnReadCount(BmobIMConversation conversation, int count) {
        //判断是否为当前进入的聊天页面，是的话则不增长未读数
        if (!conversation.getConversationId().equals(conversationId)) {
            conversation.setUnreadCount(count);
            BmobIM.getInstance().updateConversation(conversation);
        }
    }

    /**
     * 显示通知栏消息
     *
     * @param event
     */
    private void showNotifyMessage(MessageEvent event) {
        //如果当前进入的聊天页面与消息为同一个用户则不显示通知栏消息
        if (event.getConversation().getConversationId().equals(conversationId)) {
            return;
        }
        //获取消息对象以及用户对象
        final BmobIMMessage imMessage = event.getMessage();
        final BmobIMUserInfo userInfo = imMessage.getBmobIMUserInfo();
        //请求用户头像
        ImageUtils.requestImage(context, userInfo.getAvatar(), new Consumer<Bitmap>() {
            @Override
            public void accept(Bitmap bitmap) throws Exception {
                if (null == bitmap) {
                    bitmap = BitmapFactory
                            .decodeResource(context.getResources(), R.mipmap.ic_launcher);
                }
                //判断消息是否为添加好友
                Intent intent;
                if (AddFriendMessage.isAddFriend(imMessage)) {
                    intent = new Intent(context, MainActivity.class);
                } else {
                    intent = new Intent(context, ChatActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(ChatActivity.KEY_TARGET_ID, userInfo.getUserId());
                    intent.putExtras(bundle);
                }
                JNotify.NotifyBuilder builder = JNotify.build(context)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(userInfo.getName())
                        .setContentText(IM.getMessageContent(imMessage))
                        .setLargeIcon(bitmap)
                        .setDefaultLight()
                        .setDefaultVibrate()
                        .setDefaultSound()
                        .setAutoCancel(true);
                if (null != intent) {
                    builder.setContentIntent(intent);
                }
                builder.notify(userInfo.getUserId().hashCode());
            }
        });
    }

    /**
     * 判断app是否在运行
     *
     * @param context
     * @return
     */
    private boolean isAppRunning(Context context) {
        String packageName = context.getPackageName();
        String topActivityClassName = getTopActivityName(context);

        if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param context
     * @return
     */
    public String getTopActivityName(Context context) {
        String topActivityClassName = null;
        ActivityManager activityManager =
                (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
        if (runningTaskInfos != null) {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }
}